package com.plian.system.service.im.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.im.FundProjectInfoImportExcelBean;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.im.InvestmentConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.pm.property.PropertyBasicsDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.im.FundProjectAmountDetail;
import com.plian.system.entity.im.FundProjectInfo;
import com.plian.system.entity.zcgl.JzsgjgbaEntity;
import com.plian.system.excel.ImportExcelUtil;
import com.plian.system.excel.ImportResult;
import com.plian.system.mapper.im.FundProjectInfoMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.im.IFundProjectAmountDetailService;
import com.plian.system.service.im.IFundProjectInfoService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.service.yth.IFundService;
import com.plian.system.vo.im.FundProjectInfoVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.vo.zcgl.JzsgjgbaVO;
import com.plian.system.wrapper.im.FundProjectInfoWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class FundProjectInfoServiceImpl extends BaseServiceImpl<FundProjectInfoMapper, FundProjectInfo> implements IFundProjectInfoService, BaseFlowService {

	private OrgzationDao orgzationDao;

	private BaseInfoService baseInfoService;

	private PropertyBasicsDao propertyBasicsDao;

	private FundProjectInfoWrapper fundProjectInfoWrapper;

	private IFundProjectAmountDetailService fundProjectAmountDetailService;

	private IOrgService orgService;

	private ISysUserService userService;

	private IFundService  fundService;

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean saveOrUpdate(FundProjectInfo fundProjectInfo) {
		if (fundProjectInfo.getId() == null && StringUtil.isBlank(fundProjectInfo.getOrderNumber())){
			fundProjectInfo.setOrderNumber("9999");
		}
		return super.saveOrUpdate(fundProjectInfo);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			FundProjectInfo fundProjectInfo = getById(id);
			if (fundProjectInfo == null) {
				return false;
			}
		}
		return super.deleteLogic(ids);
	}

	@Override
	@Async("ttlExecutor")
	public Future<ImportResult> importExcel(String progressId, InputStream inputStream) {
		String progress = "progress";
		String key = progressId + "#half:hour";
		try {
			byte[] bytes = IOUtils.toByteArray(inputStream);
			inputStream = new ByteArrayInputStream(bytes);

			Map<String, Map<String, String>> mapRef = getRef();

            List<Object> projectList = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(1).headRowNumber(1).head(FundProjectInfoImportExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> projectList.addAll(list))).build());
			ImportExcelUtil.filterEmpty(projectList);
			ImportResult result = checkData(mapRef, projectList, progressId);
			if (!result.isSuccess()){
				CacheUtil.put(progress, progress, key, result.getMsg());
				return new AsyncResult<>(result);
			}

			int count = 0;
			int size = projectList.size();
			// 项目信息
			for (Object readExcel : projectList) {
				FundProjectInfo fundProjectInfo = (FundProjectInfo) ImportExcelUtil.getEntityByExcelBean((FundProjectInfoImportExcelBean)readExcel,new FundProjectInfo());

				LambdaQueryWrapper<FundProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(FundProjectInfo::getCreateCompanyId, TokenUtil.getTokenOrgId());
				queryWrapper.eq(FundProjectInfo::getFundName, fundProjectInfo.getFundName());
				FundProjectInfo old = getOne(queryWrapper);
				if (Optional.ofNullable(old).isPresent()){
					fundProjectInfo.setId(old.getId());
				}

				//入库
				try {
					saveOrUpdate(fundProjectInfo);
					count++;
					int value = count * 100 / size;
					CacheUtil.put(progress, progress, key, value+100);
				} catch (Exception e) {
					log.error(fundProjectInfo + "导入失败");
					CacheUtil.put(progress, progress, key,fundProjectInfo + "导入失败");
					return new AsyncResult<>(new ImportResult(false,fundProjectInfo + "导入失败"));
				}
			}

		}catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			log.error("解析失败");
			CacheUtil.put(progress, progress, key,"解析失败");
			return new AsyncResult<>(new ImportResult(false,"解析失败"));
		}

		CacheUtil.put(progress, progress, key,"导入成功");
		return new AsyncResult<>(new ImportResult(true,"导入成功"));
	}

	@Override
	public String checkName(FundProjectInfoVO fundProjectInfoVO) {
		if (StringUtil.isBlank(fundProjectInfoVO.getFundName())){
			return "基金名称为空";
		}
		fundProjectInfoVO.setFundName(StringUtil.cleanChars(fundProjectInfoVO.getFundName()));
		LambdaQueryWrapper<FundProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(FundProjectInfo::getCreateCompanyId, TokenUtil.getTokenOrgId());
		queryWrapper.eq(FundProjectInfo::getFundName, fundProjectInfoVO.getFundName());
		FundProjectInfo old = getOne(queryWrapper);

		if (!Optional.ofNullable(old).isPresent()){
			return null;
		}
		if (old.getId().equals(fundProjectInfoVO.getId())){
			return null;
		}
		return "该基金名称已存在";
	}

	@Override
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
		try {
			String fname = "基金项目导入模板";
			os = response.getOutputStream();//取得输出流
			response.reset();//清空输出流
			//下面是对中文文件名的处理
			response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
			InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/fundProjectInfoImport.xlsx");
			fname = java.net.URLEncoder.encode(fname, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("UTF-8"), "UTF-8") + ".xlsx");

			response.setContentType("application/msexcel");//定义输出类型
			int len;
			byte[] b = new byte[2048];
			while ((len = inputStream.read(b)) != -1) {
				os.write(b, 0, len);
			}
			response.setHeader("Content-Length", String.valueOf(inputStream.available()));

			inputStream.close();
			os.close();
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean submit(FundProjectInfoVO fundProjectInfoVO) {
		FundProjectInfo fundProjectInfo = fundProjectInfoWrapper.voToEntity(fundProjectInfoVO);
		if (fundProjectInfo.getId() != null){
			fundProjectAmountDetailService.removeByBaseId(fundProjectInfo.getId());
		}
		fundProjectInfo.setCode(formCodeService.getCode(FormTypeConstant.TZJHGL_SSGQJJXMQK_FORM));
		fundProjectInfo.setFormType(String.valueOf(FormTypeConstant.TZJHGL_SSGQJJXMQK_FORM));
		boolean result = saveOrUpdate(fundProjectInfo);
		if (CollectionUtil.isNotEmpty(fundProjectInfoVO.getGpDetailList())){
			for (int i = 0; i < fundProjectInfoVO.getGpDetailList().size(); i++){
				FundProjectAmountDetail amountDetail = fundProjectInfoVO.getGpDetailList().get(i);
				amountDetail.setOrderNumber(i + 1);
				amountDetail.setAmountType(InvestmentConstant.GP_AMOUNT_DETAIL_TYPE);
				amountDetail.setFundProjectId(fundProjectInfo.getId());
				amountDetail.setId(null);
			}
			fundProjectAmountDetailService.saveBatch(fundProjectInfoVO.getGpDetailList());
		}
		if (CollectionUtil.isNotEmpty(fundProjectInfoVO.getLpDetailList())){
			for (int i = 0; i < fundProjectInfoVO.getLpDetailList().size(); i++){
				FundProjectAmountDetail amountDetail = fundProjectInfoVO.getLpDetailList().get(i);
				amountDetail.setOrderNumber(i + 1);
				amountDetail.setAmountType(InvestmentConstant.LP_AMOUNT_DETAIL_TYPE);
				amountDetail.setFundProjectId(fundProjectInfo.getId());
				amountDetail.setId(null);
			}
			fundProjectAmountDetailService.saveBatch(fundProjectInfoVO.getLpDetailList());
		}
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(fundProjectInfo.getId()), fundProjectInfo.getFormType(), processVariable);
		return result;
	}

	@Override
	public FundProjectInfoVO detail(FundProjectInfo fundProjectInfo) {
		FundProjectInfo detail = getOne(Condition.getQueryWrapper(fundProjectInfo));
		if (detail == null){
			return null;
		}
		FundProjectInfoVO fundProjectInfoVO = fundProjectInfoWrapper.entityToVO(detail);
		Map<Integer, List<FundProjectAmountDetail>> amountDetailMap = fundProjectAmountDetailService.getMapByBaseId(detail.getId());
		fundProjectInfoVO.setGpDetailList(amountDetailMap.get(InvestmentConstant.GP_AMOUNT_DETAIL_TYPE));
		fundProjectInfoVO.setLpDetailList(amountDetailMap.get(InvestmentConstant.LP_AMOUNT_DETAIL_TYPE));
		return fundProjectInfoVO;
	}

	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public String saveFundProjectInfos(String data){
		YthResult ythResult = new YthResult();
		//成功的id集合
		List<String> successIds = new ArrayList<>();
		//失败的id集合
		List<String> failIds = new ArrayList<>();
		//失败的原因
		List<String> failReasons = new ArrayList<>();
		//将json字符串转换成list
		List<FundProjectInfoVO> dataList = JSON.parseArray(data, FundProjectInfoVO.class);
		//判断list是否为空
		if (CollectionUtil.isNotEmpty(dataList)){
			//组织map
			Map<String, String> orgSourceMap = orgService.getSourceId();
			//根据datasourceIds 查询出所有的数据
			List<FundProjectInfo> list = list(new LambdaQueryWrapper<FundProjectInfo>().in(FundProjectInfo::getDataSourceId, dataList.stream().map(FundProjectInfo::getDataSourceId).toArray()));
			//如果数据库中有数据，就更新，没有就新增
			for (FundProjectInfoVO entity:dataList) {
				String dataSourceId = entity.getDataSourceId();
				transfer(entity,orgSourceMap);
				if (CollectionUtil.isNotEmpty(list)){
					List<String> olIds = list.stream().map(FundProjectInfo::getDataSourceId).collect(Collectors.toList());
					//判断数据库中是否有数据
					if (olIds.contains(dataSourceId)){
						for (FundProjectInfo oldEntity:list) {
							if (dataSourceId.equals(oldEntity.getDataSourceId())) {
								successIds.add(dataSourceId);
								entity.setId(oldEntity.getId());
								entity.setDataSource(YthConstant.DATA_NINGBO);
								submit(entity);
								list.remove(oldEntity);
								break;
							}
						}
					}else {
						//如果数据库中没有数据，就新增
						entity.setDataSource(YthConstant.DATA_NINGBO);
						submit(entity);
						successIds.add(entity.getDataSourceId());
					}
				}else {
					entity.setDataSource(YthConstant.DATA_NINGBO);
					submit(entity);
					successIds.add(entity.getDataSourceId());
				}
			}
		} else {
			failReasons.add("数据为空");
		}
		ythResult.setSuccessIds(successIds);
		ythResult.setFailIds(failIds);
		ythResult.setFailReason(StringUtils.join(failReasons, ";"));
		//ythResult转换成json字符串
		return JSON.toJSONString(ythResult);
	}


	private void transfer(FundProjectInfoVO entity, Map<String, String> orgSourceMap){
		Optional.ofNullable(entity.getCompanyId()).ifPresent(m ->
				{
					String orgId = orgSourceMap.get(m);
					if (StringUtil.isNotBlank(orgId)){
						entity.setCompanyId(orgId);
						entity.setCreateCompanyId(orgId);
					}
				}
		);

		Optional.ofNullable(entity.getInvestmentSubject()).ifPresent(m ->
				{
					String orgId = orgSourceMap.get(m);
					if (StringUtil.isNotBlank(orgId)){
						entity.setInvestmentSubject(orgId);
					}
				}
		);
	}

	@Override
	public List<FundProjectInfoVO> detailList(List<FundProjectInfo> fundProjectInfos) {
		if (CollectionUtil.isEmpty(fundProjectInfos)){
			return Collections.emptyList();
		}
		Map<String, List<FundProjectAmountDetail>> amountDetailMap = fundProjectAmountDetailService
				.getMapByBaseIds(fundProjectInfos.stream().map(FundProjectInfo::getId).collect(Collectors.toList()));
		List<FundProjectInfoVO> fundProjectInfoVOS = fundProjectInfoWrapper.entityToVO(fundProjectInfos);
		for (FundProjectInfoVO infoVO : fundProjectInfoVOS){
			infoVO.setGpDetailList(amountDetailMap.get(infoVO.getId() + StringPool.UNDERSCORE + InvestmentConstant.GP_AMOUNT_DETAIL_TYPE));
			infoVO.setLpDetailList(amountDetailMap.get(infoVO.getId() + StringPool.UNDERSCORE + InvestmentConstant.LP_AMOUNT_DETAIL_TYPE));
		}
		return fundProjectInfoVOS;

	}

	private Map<String,Map<String,String>> getRef() {
		Map<String, Map<String, String>> mapRefs = new HashMap<>(16);
		mapRefs.put("fundCategoryRef",baseInfoService.getChildMap(ValueSetConstant.FUND_CATEGORY));

		mapRefs.put("manageModeRef",baseInfoService.getChildMap(ValueSetConstant.MANAGE_MODE));

		mapRefs.put("fundTypeRef",baseInfoService.getChildMap(ValueSetConstant.FUND_TYPE));

		mapRefs.put("organizationFormRef",baseInfoService.getChildMap(ValueSetConstant.ORGANIZATION_FORM));

		mapRefs.put("fundStatusRef",baseInfoService.getChildMap(ValueSetConstant.FUND_STATUS));

		mapRefs.put("managerTypeRef",baseInfoService.getChildMap(ValueSetConstant.MANAGER_TYPE));

		mapRefs.put("fundNatureRef",baseInfoService.getChildMap(ValueSetConstant.FUND_NATURE));

		Map<String,String> unitRef = new HashMap<>(512);
		Map<String, String> propertyRef = new HashMap<>(2048);
		Map<String, String> affiliatedOrgFullNameRef = new HashMap<>(2048);
		try{
			List<PageData> allOrgs =  orgzationDao.list(null);
			if (CollectionUtil.isNotEmpty(allOrgs)){
				for (PageData pageData : allOrgs){
					unitRef.put((String)pageData.get("name"), (String)pageData.get("id"));
				}
			}
			List<PageData> allProperty =  propertyBasicsDao.list(null);
			if (CollectionUtil.isNotEmpty(allProperty)){
				for (PageData property : allProperty){
					propertyRef.put((String)property.get("orgName"), (String)property.get("id"));
					affiliatedOrgFullNameRef.put((String)property.get("id"), (String)property.get("affiliatedOrgFullName"));
				}
			}
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		mapRefs.put("unitRef", unitRef);
		mapRefs.put("propertyRef", propertyRef);
		mapRefs.put("AffiliatedOrgFullNameRef",affiliatedOrgFullNameRef);
		return mapRefs;
	}

	private ImportResult checkData(Map<String, Map<String,String>> mapRef, List<Object> readExcels, String progressId) {
		ImportResult importResult = new ImportResult(true,"");

		StringBuilder msg = new StringBuilder();

		if (CollectionUtil.isNotEmpty(readExcels)) {
			for (Object readExcel : readExcels) {
				FundProjectInfoImportExcelBean excelBean = (FundProjectInfoImportExcelBean) readExcel;
				int index = readExcels.indexOf(readExcel);
				//判空
				msg.append(ImportExcelUtil.checkEmpty("2", "所属集团",
						excelBean.getCompanyId(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "基金标准全称",
						excelBean.getFundName(), index).getMsg());
				//去除多余空格
				if(StringUtil.isNoneBlank(excelBean.getFundName())){
					excelBean.setFundName(StringUtil.cleanChars(excelBean.getFundName()));
				}
				msg.append(ImportExcelUtil.checkEmpty("2", "基金性质",
						excelBean.getFundNature(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "管理方式",
						excelBean.getManageMode(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "基金类型",
						excelBean.getFundType(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "组织形式",
						excelBean.getOrganizationForm(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "成立日期",
						excelBean.getStartTime(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "到期日期",
						excelBean.getEndTime(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "基金状态",
						excelBean.getEndTime(), index).getMsg());
//				msg.append(ImportExcelUtil.checkEmpty("2", "内部收益率",
//						excelBean.getInternalYieldRate(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "GP(含出资额)",
						excelBean.getGp(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "LP(含出资额)",
						excelBean.getLp(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "管理人类型",
						excelBean.getManagerType(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "基金规模",
						excelBean.getFundScale(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "认缴出资额",
						excelBean.getSubscribedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "本公司认缴金额",
						excelBean.getCompanyContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "已实缴出资额",
						excelBean.getContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "本年度已实缴出资额",
						excelBean.getYearContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "本公司已出资额",
						excelBean.getHasContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "本公司本年度已出资额",
						excelBean.getCompanyYearContributedCapital(), index).getMsg());

				//类型判断
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_DATE, "2", "开始时间",
						excelBean.getStartTime(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_DATE, "2", "结束时间",
						excelBean.getEndTime(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "内部收益率",
						excelBean.getInternalYieldRate(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "GP(含出资额)",
						excelBean.getGp(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "LP(含出资额)",
						excelBean.getLp(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "认缴出资额",
						excelBean.getSubscribedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "本公司认缴金额",
						excelBean.getCompanyContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "已实缴出资额",
						excelBean.getContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "本年度已实缴出资额",
						excelBean.getYearContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "本公司已出资额",
						excelBean.getHasContributedCapital(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "本公司本年度已出资额",
						excelBean.getCompanyYearContributedCapital(), index).getMsg());

				//判断完类型若有错直接返回
				if (msg.toString().length() > 0) {
					return new ImportResult(false, msg.toString());
				}
			}
			//判断完类型若有错直接返回
			if (msg.toString().length() > 0) {
				return new ImportResult(false, msg.toString());
			}

			//对象和字典是否存在校验
			int size = readExcels.size();
			int count = 0;
			for (Object readExcel : readExcels) {
				FundProjectInfoImportExcelBean excelBean = (FundProjectInfoImportExcelBean) readExcel;
				int index = readExcels.indexOf(readExcel);
				//对象和字典是否存在校验
				//单位名称
				excelBean.setCompanyId(StringUtil.cleanChars(excelBean.getCompanyId()));
				if (mapRef.get("propertyRef").containsKey(excelBean.getCompanyId())) {
					excelBean.setCompanyId(mapRef.get("propertyRef").get(excelBean.getCompanyId()));
				} else if (!StringUtil.isEmpty(excelBean.getCompanyId())) {
					msg.append("sheet2第" + index + "行(所属集团=" + excelBean.getCompanyId() + ")在系统中不存在\n");
				}
				if (StringUtil.isNoneBlank(excelBean.getCompanyId())&&mapRef.get("AffiliatedOrgFullNameRef").containsKey(excelBean.getCompanyId())) {
					excelBean.setAffiliatedOrgFullName(mapRef.get("AffiliatedOrgFullNameRef").get(excelBean.getCompanyId()));
				}else{
					excelBean.setAffiliatedOrgFullName("");
				}


//				//项目性质
//				if (StringUtil.isNotBlank(excelBean.getFundCategory())) {
//					if (!mapRef.get("fundCategoryRef").containsKey(excelBean.getFundCategory())) {
//						msg.append("sheet2第" + index + "行(基金类别=" + excelBean.getFundCategory() + ")在系统中不存在\n");
//					}
//				}
				//管理方式
				if (StringUtil.isNotBlank(excelBean.getManageMode())) {
					if (!mapRef.get("manageModeRef").containsKey(excelBean.getManageMode())) {
						msg.append("sheet2第" + index + "行(管理方式=" + excelBean.getManageMode() + ")在系统中不存在\n");
					}
				}
				//基金类型
				if (StringUtil.isNotBlank(excelBean.getFundType())) {
					if (!mapRef.get("fundTypeRef").containsKey(excelBean.getFundType())) {
						msg.append("sheet2第" + index + "行(基金类型=" + excelBean.getFundType() + ")在系统中不存在\n");
					}
				}
				//组织形式
				if (StringUtil.isNotBlank(excelBean.getOrganizationForm())) {
					if (!mapRef.get("organizationFormRef").containsKey(excelBean.getOrganizationForm())) {
						msg.append("sheet2第" + index + "行(组织形式=" + excelBean.getOrganizationForm() + ")在系统中不存在\n");
					}
				}
				//基金状态
				if (StringUtil.isNotBlank(excelBean.getFundStatus())) {
					if (!mapRef.get("fundStatusRef").containsKey(excelBean.getFundStatus())) {
						msg.append("sheet2第" + index + "行(基金状态=" + excelBean.getFundStatus() + ")在系统中不存在\n");
					}
				}
				//管理人类型
				if (StringUtil.isNotBlank(excelBean.getManagerType())) {
					if (!mapRef.get("managerTypeRef").containsKey(excelBean.getManagerType())) {
						msg.append("sheet2第" + index + "行(管理人类型=" + excelBean.getManagerType() + ")在系统中不存在\n");
					}
				}

				//基金性质
				if (StringUtil.isNotBlank(excelBean.getFundNature())) {
					if (!mapRef.get("fundNatureRef").containsKey(excelBean.getFundNature())) {
						msg.append("sheet2第" + index + "行(基金性质=" + excelBean.getFundNature() + ")在系统中不存在\n");
					}
				}

				count++;
				int value = count * 100 / size;
				CacheUtil.put("progress","progress",progressId, value);
			}
		}

		//统一放置报错
		if (msg.toString().length()>0) {
			importResult = new ImportResult(false, msg.toString());
		}
		return importResult;

	}

	@Override
	public HashMap<String, Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String, Object>();
	}

	@Override
	public Boolean finish(String id) {
		FundProjectInfo entity = getById(id);
		entity.setApprovedUser(TokenUtil.getTokenUserId());
		Date now = DateUtil.now();
		entity.setApprovedTime(now);
		updateById(entity);

		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState);
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), FormStatusConstant.UNREVIEWED);
	}

	@Override
	public List<PageData> findByIds(List<String> formIds) {
		List<FundProjectInfo> list = list(new LambdaQueryWrapper<FundProjectInfo>().in(FundProjectInfo::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA))));
		List<FundProjectInfoVO> fundProjectInfoVOS = fundProjectInfoWrapper.entityToVO(list);
		List<PageData> pageDataList = new ArrayList<>();
		fundProjectInfoVOS.forEach(vo -> {
			PageData pd = new PageData();
			pd.put("id", vo.getId());
			pd.put("UNITNAME", vo.getCompanyName());
			pd.put("APPLICANTNAME", vo.getCreateUserName());
			pd.put("applicantId", vo.getCreateUser());
			pd.put("applyOrganizationId", vo.getCompanyId());
			pd.put("formType", FormTypeConstant.TZJHGL_SSGQJJXMQK_FORM);
			pd.put("orgName", vo.getCompanyName());
			pageDataList.add(pd);
		});
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Collections.singletonList(FormTypeConstant.TZJHGL_SSGQJJXMQK_FORM);
	}

	private Boolean handleStatus(Long id, int updateStatus) {
		try {
			FundProjectInfo entity = getById(id);
			entity.setStatus(updateStatus);
			updateById(entity);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}
}
